#
# PVCSPrefsDialog.py
#
# this class implements the dialog for changing the archive suffix
# rules inside the PVCS config file
#
# Author: Uwe Stieber
# Copyright (c) 1998, 1999 TakeFive Software, Salzburg
#

# some system modules
import sys
import os
import string

# debug variable
import PVCSConstants

# some SNiFF+ modules
from etgui import *
from PageLayout import *
import CmdNo
import ListEditor

# the dialog tab sheet classes

# the suffix rule dictionary editor
class SuffixRuleEditor(ListEditor.AbstrListEditor):
	"""A class that does simple dictionary editing"""
	DoSwap=None
	
	# class private variables
	__dict = None	# the dictionary Store
	__model = None  # the used Model (Data Store)
	__path = None   # the path to the data inside the model
	
	# Constructor
	def __init__(self, aModel, aPath):
		# intialize variables
		self.__dict = None
		self.__model = aModel
		self.__path = aPath
		# call baseclass constructor
		ListEditor.AbstrListEditor.__init__(self)
			
	# perform the SetItems call
	def DoSetItems(self, dict):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoSetItems@B"
		# save the dictionary
		self.__dict = dict
		# build the items list
		self.items = []		# clear the list ;)
		for aKey in self.__dict.keys():
			spaceInbetween = "";
			if len(aKey) < 10:
				spaceInbetween = " "*(10-len(aKey))
			self.items.append("%s" % aKey + spaceInbetween + " --> %s" % self.__dict[aKey])
		# sort the items list
		self.items.sort()
		if PVCSConstants.TEST:
			print "(PVCS Suffix Rule Editor)\tresulted dictionary: @B@r",
			print self.__dict,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)\tresulted items list: @B@r",
			print self.items,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)@B@r<<<@x DoSetItems@B"
		return self.items
				
	def DoMakeItem(self,key_value):
		if PVCSConstants.TEST:
			print "(PVCS Suffix Rule Editor)@B@g>>>@x DoMakeItem@B"
		try:
			key,value=key_value
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\tkey_value = @B@b(%s, %s)@x@B" % key_value
		except (TypeError,ValueError):
			key=key_value
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\tkey_value = @B@b%s@x@B" % key_value
		textStyle = eFacePlain | eFaceBold
		aTextItem = None
		if not self.IsNormal(key):
			aTextItem = StyledTextItem(str(key),
									font=Font(
											gSysFont.Fid(),
											gSysFont.Size(),
											textStyle
										),
										ink=RGBInk(217, 0, 33)
									)
		else:
			aTextItem = TextItem(str(key),
									font=Font(
										gSysFont.Fid(),
										gSysFont.Size(),
										textStyle
										)
									)
		
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@r<<<@x DoMakeItem@B"
		return aTextItem

	# check, if we can delete the currently selected items
	# the only item, which cannot deleted, is the item which contains '.?'
	allow_delete=0
	def CanDelete(self,i):
		if self.allow_delete:
			self.allow_delete = 0
			return 1
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x CanDelete (index = %d)@B" % i
		return self.IsNormal(self.items[i])

	# replace is only valid for deletable items
	# overwrite CanDelete
	def ForceReplace(self,val):
		self.allow_delete = 1
		self.Replace(val)
		self.allow_delete = 0
		
	# check, if it is a 'normal' item
	# the only 'non-normal' item is the item which contains '.?'
	def IsNormal(self, aItem):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x IsNormal (aItem = '%s')@B" % aItem
		return aItem[:2] != ".?"
	
	# perform delete action	
	def DoDelete(self,i):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoDelete (index = %d)@B" % i
		key=string.split(self.items[i])[0]
		del self.__dict[key]
		del self.items[i]
		self.updateModel()
		if PVCSConstants.TEST:
			print "(PVCS Suffix Rule Editor)\tresulted dictionary: @B@r",
			print self.__dict,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)\tresulted items list: @B@r",
			print self.items,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)@B@r<<<@x DoDelete@B"
		return 1

	# perform insert action
	def DoInsert(self, i, key_value):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoInsert (index = %d)@B" % i
		usedKeyValue = ""
		try:
			key,value = key_value
			if len(key) > 4:
				key = key[:4]
			usedKeyValue = "%s" % key + " "*(5-len(key)) + " --> %s" % value
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\tkey_value = @B@b(%s, %s)@x@B" % key_value
		except (TypeError,ValueError):
			key = string.split(key_value)[0]
			value = string.split(key_value)[2]
			usedKeyValue = key_value
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\tkey = @B@b%s@x@B, value = @B@b%s@x@B" % (key, value)
		k=-1
		for k in range(len(self.items)):
			if self.items[k] > key:
				break
		else:
			k=k+1
		# check for double keys
		if not self.__dict.has_key(key):
			self.items.insert(k, usedKeyValue)
			self.__dict[key] = value
			self.updateModel()
		else:
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\tFound double keys: %s; no insert action performed !" % key
		if PVCSConstants.TEST:
			print "(PVCS Suffix Rule Editor)\tresulted dictionary: @B@r",
			print self.__dict,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)\tresulted items list: @B@r",
			print self.items,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)@B@r<<<@x DoInsert (k = %d)@B" % k
		return k
		
	# builds the edit dialog
	def ShowEditDialog(self, how, defaultExtension, defaultRule):
		model = PotGuiModel()
		model.SetValue("Extension", defaultExtension)
		model.SetValue("Rule", defaultRule)
		retval=ShowSubDialog("%s %s" % (how, "Suffix Rule"),
			model,
			MakeSectionLayout(
				Form(
					items=[
						"Extension:", PotTextField("Extension"),
						"Suffix Rule:", PotTextField("Rule")
					]
				)
			)
		)
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)\tShowEditDialog @BretValue: @b%d@x@B" % retval
		if retval:
			newExtension = model.GetValue("Extension")
			newRule = model.GetValue("Rule")
			# check length of extension
			spaceInbetween = "";
			if len(newExtension) < 10:
				spaceInbetween = " "*(10-len(newExtension))
			return "%s" % newExtension + spaceInbetween + " --> %s" % newRule
		else:
			return None

	# perform edit action
	def DoEdit(self, i):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoEdit (index = %d)@B" % i
		# get the item at position 'i'
		extension = string.split(self.items[i])[0]
		rule = string.split(self.items[i])[2]
		retValue = self.ShowEditDialog("Edit", extension, rule)
		if retValue != None:
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\t@BDialog result: @b%s@x@B" % retValue
			newExtension = string.split(retValue)[0]
			newRule = string.split(retValue)[2]
			# anything changed ?
			if newExtension == extension and newRule == rule:
				# nothing changed, do nothing
				if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)\tnothing changed ! Do nothing !"
				pass
			else:
				# something has changed
				if newExtension != extension:
					# key has changed
					if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)\tKey has changed ! Update dictionary and items list !"
					# update view, dictionary and items list
					self.ForceReplace(retValue)
				else:
					# key hasn't changed, but rule has changed
					if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)\tKey hasn't changed, but rule has changed ! Update dictionary and items list !"
					# update view, dictionary and items list
					self.ForceReplace(retValue)					
		if PVCSConstants.TEST:
			print "(PVCS Suffix Rule Editor)\tresulted dictionary: @B@r",
			print self.__dict,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)\tresulted items list: @B@r",
			print self.items,
			print "@x@B"
			print "(PVCS Suffix Rule Editor)@B@r<<<@x DoEdit@B"
		return 1

	# perform new action
	def DoNew(self, i):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoNew (index = %d)@B" % i
		retValue = self.ShowEditDialog("New", "", "")
		if retValue != None:
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\t@BDialog result: @b%s@x@B" % retValue
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@r<<<@x DoNew@B"
		return retValue
		
	# perform copy action
	def DoCopy(self, i):
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@g>>>@x DoCopy (index = %d)@B" % i
		# get the item at position 'i'
		extension = self.FindUniqueName(string.split(self.items[i])[0])
		rule = string.split(self.items[i])[2]
		retValue = self.ShowEditDialog("Copy", extension, rule)
		if retValue != None:
			if PVCSConstants.TEST:
				print "(PVCS Suffix Rule Editor)\t@BDialog result: @b%s@x@B" % retValue
		if PVCSConstants.TEST: print "(PVCS Suffix Rule Editor)@B@r<<<@x DoCopy@B"
		return retValue

	# overwrite the Edit Button creation	
	def MakeEditButton(self):
		if self.DoEdit:
			return self.NewButton("Edit...", self._Edit, self.CanEdit)
			
	# find a unique name for copy
	def FindUniqueName(self, orgName):
		newName = orgName
		i = 1
		# search the dictionary until a unique name is found
		while self.__dict.has_key(newName):
			newName = "%s__%i" % (newName, i)
			i = i + 1
		return newName
		
	# hold the GUI model up to date
	def updateModel(self):
		self.__model.SetValue(self.__path, self.__dict)

# some functions to create the dialog
def MakeSuffixRuleSheet(model, path):
	# create the editor
	editor = SuffixRuleEditor(model, path)
	# gather the items
	editor.SetItems(model.GetValue(path))
	return MakeSectionLayout(
				MakePageLayout(eVObjHExpand|eVObjVExpand,
					MakeListEditorLayout(editor)
				),	# MakePageLayout
				MakeBorderedSectionLayout("Archive searching",
					Form(
						items=[
							"VCS Adapter specific subdirectory: ",
							PotTextField("AdapterSubDir")
						] # items
					) # Form
				) # MakeBorderedSectionLayour
			)	# MakeSectionLayout
	
class ToggleButtonEnabler(FieldEnabler):
	def IsEnabled(self,value):
		return value=="Enable"
		
def MakeGeneralPrefsSheet(model):
	# create the page fields and set the attributes
	diagnostic = model.GetValue("Option_Diagnostic")
	if diagnostic - 500 >= 0:
		model.SetValue("Diag_500", 1)
		diagnostic = diagnostic - 500
	else:
		model.SetValue("Diag_500", 0)
	if diagnostic - 4 >= 0:
		model.SetValue("Diag_4", 1)
		diagnostic = diagnostic - 4
	else:
		model.SetValue("Diag_4", 0)
	if diagnostic - 2 >= 0:
		model.SetValue("Diag_2", 1)
		diagnostic = diagnostic - 2
	else:
		model.SetValue("Diag_2", 0)
	if diagnostic - 1 >= 0:
		model.SetValue("Diag_1", 1)
		diagnostic = diagnostic - 1
	else:
		model.SetValue("Diag_1", 0)
	efDiagnostic1 = PotGuiToggleButton("Diag_1", " 1")
	efDiagnostic2 = PotGuiToggleButton("Diag_2", " 2")
	efDiagnostic4 = PotGuiToggleButton("Diag_4", " 4")
	efDiagnostic500 = PotGuiToggleButton("Diag_500", " 500")
	cbOptionQuiet = PotGuiToggleButton("Option_Quiet", "Display minimal PVCS messages")
	cbOptionSignOn = PotGuiToggleButton("Option_SignOn", "Display PVCS copyright and version")
	cbVCSDebug = PotGuiToggleButton("VCSDebug", "Show basic adapter debug information")
	cbPVCSDebug = PotGuiToggleButton("PVCSDebug", "Show additional detailed debug information")
	cbVLOGDebug = PotGuiToggleButton("VLOGDebug", "Show log parsing debug information")
	#model.SetValue("VLOGDebug.enable", "Disabled")
	#ToggleButtonEnabler(model, "VLOGDebug.enable",
	#	items=[
	#		cbVLOGDebug
	#	] # items
	#) # ToggleButtonEnabler
	return MakePageLayout(eVObjHExpand | eVObjVExpand,
		MakeBorderedSectionLayout("Information settings",
			Form (
				items=[
					VBox(
						items=[
							HBox(
								items=[
									"Diagnostic Level:",
									Filler(gPoint5),
									efDiagnostic1,
									Filler(gPoint5),
									efDiagnostic2,
									Filler(gPoint5),
									efDiagnostic4,
									Filler(gPoint5),
									efDiagnostic500
								] # items
							), # HBox
							Filler(gPoint5),
							VBox(
								items=[
									cbOptionQuiet,
									cbOptionSignOn
								] # items
							) # VBox
						] # items
					) # VBox
				] # items
			) # Form
		), # MakeBorderedSectionLayout
		MakeBorderedSectionLayout("Adapter Debug settings",
			Form (
				items=[
					VBox(
						items=[
							cbVCSDebug,
							cbPVCSDebug,
							cbVLOGDebug
						] # items
					) # VBox
				] # items
			) # Form
		) # MakeBorderedSectionLayout
	) # MakePageLayout
	
def MakeConfigFilePrefsSheet(model):
	# create the page field and set the attributes
	aMasterConfigFileSelector = PotGuiFileSelector("masterCFGFile", gTextFieldLen, "PVCS Config File")
	aProjectConfigFileSelector = PotGuiFileSelector("projectCFGFile", gTextFieldLen, "PVCS Config File")
	# create tab page layout
	return MakeSectionLayout(
		MakePageLayout(eVObjHExpand|eVObjVExpand,
			MakeBorderedSectionLayout("PVCS related Config Files",
				Form(
					items=[
						"Master Config File", aMasterConfigFileSelector,
						"Project Config File", aProjectConfigFileSelector
					]	# items
				)	# Form
			),	# MakeBorderedSectionLayout
			MakeBorderedSectionLayout("SNiFF+ related Config Files",
				Form(
					items=[
						VBox(
							items=[
								"SNiFF+ Master Config File:",
								TextItem("%s" % model.GetValue("SNiFF+ Master Config File"))
							] # items
						) # VBox
					]	# items
				)	# Form
			)	# MakeBorderedSectionLayout
		)	# MakePageLayout
	)	# MakeSectionLayout

def ShowPrefsDialog(aInputSuffixRuleDict,
					sniffMasterFile,
					pvcsMasterFile,
					pvcsProjectFile,
					VCSDebug,
					PVCSDebug,
					VLOGDebug,
					DiagnosticLevel,
					QuietFlag,
					SignOnFlag,
					AdapterSubDir
					):
	if PVCSConstants.TEST: print "(PVCS Prefs Dialog)@B@g>>>@x ShowPrefsDialog@B"
	# Create a model used in the dialog to store data
	model = PotGuiModel()
	# Set the shown values
	# General View
	model.SetValue("Option_Diagnostic", DiagnosticLevel)
	model.SetValue("Option_Quiet", QuietFlag)
	model.SetValue("Option_SignOn", SignOnFlag)
	model.SetValue("VCSDebug", VCSDebug)
	model.SetValue("PVCSDebug", PVCSDebug)
	model.SetValue("VLOGDebug", VLOGDebug)
	# Config File View
	model.SetValue("masterCFGFile", pvcsMasterFile) 
	model.SetValue("projectCFGFile", pvcsProjectFile)
	model.SetValue("SNiFF+ Master Config File", sniffMasterFile)
	# Suffix Rule view
	model.SetValue("Suffix Rules", aInputSuffixRuleDict)
	model.SetValue("AdapterSubDir", AdapterSubDir)
	aPanel = PotGuiPanel(gPoint6,eVObjVExpand|eVObjHExpand)
	aPanel.AddPage(MakeHeader("General", "General integration settings",
							MakeGeneralPrefsSheet(model)), 0, "General settings")
	# disabled at 22.06.1999 by USI
	#aPanel.AddPage(MakeHeader("Config Files", "Used PVCS config files",
	#						MakeConfigFilePrefsSheet(model)), 1, "Config Files")
	aPanel.AddPage(MakeHeader("Suffix Rules", "Toggle the PVCS suffix rules",
							MakeSuffixRuleSheet(model, "Suffix Rules")), 0, "Archive File Searching")
	aPanel.Update()
	retval=ShowSubDialog("PVCS Integration Preferences",
		model,
		MakePageLayout(eVObjHExpand|eVObjVExpand,
			aPanel
		) # MakePageLayout
	) # ShowSubDialog
	if retval:
		# Ok - Button Pressed
		# calulcate the Diagnostic value
		diagnostic = 0
		if model.GetValue("Diag_1"): diagnostic = diagnostic + 1
		if model.GetValue("Diag_2"): diagnostic = diagnostic + 2
		if model.GetValue("Diag_4"): diagnostic = diagnostic + 4
		if model.GetValue("Diag_500"): diagnostic = diagnostic + 500
		model.SetValue("Option_Diagnostic", diagnostic)
	else:
		# Cancel button pressed
		model = None
	if PVCSConstants.TEST: print "(PVCS Prefs Dialog)\tShowPrefsDialog @BretValue: @b%d@x@B" % retval
	if PVCSConstants.TEST: print "(PVCS Prefs Dialog)@B@r<<<@x ShowPrefsDialog@B"
	return model
	
def Show(aInputSuffixRuleDict,
		sniffMasterFile,
		pvcsMasterFile,
		pvcsProjectFile,
		VCSDebug,
		PVCSDebug,
		VLOGDebug,
		DiagnosticLevel,
		QuietFlag,
		SignOnFlag,
		AdapterSubDir
		):
	if PVCSConstants.TEST: print "(PVCS Prefs Dialog)@B@g>>>@x Show@B"
	model = ShowPrefsDialog(
			aInputSuffixRuleDict,
			sniffMasterFile,
			pvcsMasterFile,
			pvcsProjectFile,
			VCSDebug,
			PVCSDebug,
			VLOGDebug,
			DiagnosticLevel,
			QuietFlag,
			SignOnFlag,
			AdapterSubDir
		)
	if PVCSConstants.TEST: print "(PVCS Prefs Dialog)@B@r<<<@x Show@B"
	return model
